package com.starview.star.compiler.util;

public class ByteBuilder
{
  byte[] data;
  int pos;

  public void append(byte[] app)
  {
    if (data == null) {
      data = app;
      pos = app.length;
    } else {
      if (app.length + pos >= data.length) {
        byte[] nData = new byte[data.length + app.length + data.length / 2];
        for (int ix = 0; ix < pos; ix++)
          nData[ix] = data[ix];
        data = nData;
      }
      for (int ix = 0; ix < app.length; ix++)
        data[pos++] = app[ix];
    }
  }

  public void append(byte[] app, int from, int count)
  {
    if (data == null) {
      data = new byte[count];
      pos = 0;
      for (int ix = from; ix < count; ix++)
        data[pos++] = app[ix];
    } else {
      if (app.length + pos >= data.length) {
        byte[] nData = new byte[data.length + app.length + data.length / 2];
        for (int ix = 0; ix < pos; ix++)
          nData[ix] = data[ix];
        data = nData;
      }
      for (int ix = from; ix < count; ix++)
        data[pos++] = app[ix];
    }
  }
  public void append(byte b)
  {
    if (data == null) {
      data = new byte[10];
      pos = 0;
    }
    if (pos >= data.length) {
      byte[] nData = new byte[data.length + data.length / 2 + 1];
      for (int ix = 0; ix < pos; ix++)
        nData[ix] = data[ix];
      data = nData;
    }
    data[pos++] = b;
  }

  public byte[] toBytes()
  {
    if (data == null)
      return new byte[] {};
    else if (pos < data.length) {
      byte[] output = new byte[pos];
      for (int ix = 0; ix < pos; ix++)
        output[ix] = data[ix];
      return output;
    } else
      return data;
  }
}
